#coding=utf-8
"""命令行火车票查看器

Usage:
    tickets [-gdtkz] <from> <to> <date>

Options:
    -h,--help   显示帮助菜单
    -g          高铁
    -d          动车
    -t          特快
    -k          快速
    -z          直达

Example:
    tickets 北京 上海 2016-10-10
    tickets -dg 成都 南京 2016-10-10
"""
#from stations import stations
import stations_function
from docopt import docopt
import requests
from prettytable import PrettyTable
import sys
from datetime import datetime
from colorama import Fore
#chcp 65001
#---------------------------------------------------------
reload(sys)
sys.setdefaultencoding('utf-8')
#----------------------------------------------------------
def cli():
    arguments = docopt(__doc__)
    revert_stations = []
    from_station = stations_function.getKey(arguments['<from>'].decode('gbk'))
    to_station = stations_function.getKey(arguments['<to>'].decode('gbk'))
    date = arguments['<date>']
    optional = ''.join([key for key, value in arguments.items() if value is True])
    if(None == from_station or None == to_station):
        print u"请输入有效的名称"
        exit()
    try:
        if datetime.strptime(date, '%Y-%m-%d') < datetime.now():
            raise ValueError
    except:
        print u"请输入有效日期"
        exit()
    # 构建URL
    url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format(
        date, from_station, to_station
    )
    head = {
        'Host': 'kyfw.12306.cn',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
    }
    r = requests.get(url, verify=False, headers = head)
    raw_trains = r.json()['data']['result']
    pt = PrettyTable()
    title = ['车次','车站','时间','历时','商务座','一等座','二等座','软卧','硬卧','硬座','无座']
    pt._set_field_names(title)
    #pt._set_field_names('1 2 3 4 5 6 7 8 9 10 11'.split())
    for raw_train in raw_trains:
        date_list = raw_train.split('|')
        train_no = date_list[3]
        if optional and train_no[0].lower() not in optional:
            continue
        start_time = date_list[8]
        arrive_time = date_list[9]
        from_station_code = date_list[6]
        to_station_code = date_list[7]
        from_station_name = stations_function.getValue(from_station_code)
        to_station_name = stations_function.getValue(to_station_code)
        time_duration = date_list[10]
        sw_class_seat = date_list[32] or '--'
        first_class_seat = date_list[31] or '--'
        second_class_seat = date_list[30] or '--'
        soft_sleep = date_list[23] or '--'
        hard_sleep = date_list[28] or '--'
        hard_seat = date_list[29] or '--'
        no_seat = date_list[33] or '--'
        content = [train_no, '\n'.join([from_station_name, to_station_name]), '\n'.join([start_time, arrive_time]), time_duration, sw_class_seat, first_class_seat, second_class_seat, soft_sleep, hard_sleep, hard_seat, no_seat]
        pt.add_row(content)
    print pt


#-------------------------------------------
if __name__ == '__main__':
    cli()

